/* Controllers */

var appControllers = angular.module('appControllers', []);

// 微信服务请求
appControllers.controller('FwqqCtrl-wx', function($rootScope, $scope, $http,$ionicActionSheet, $ionicPopup,$ionicLoading,$state, Camera) {

	App.setScope($scope);
	App.userquery();

	var user = Session.loadObject("user");
	if(user) {
		$scope.userinfo = user;
	}

	$scope.formData={};
	//$scope.formData.category='SERVICEREQ_CATEGORY_10';
	$scope.showimgdiv = false;


	$scope.selecttype = function(typename){
		$scope.formData.title=typename; //+"-微信";

		switch (typename){
			case '桌面OA服务':
			case '会议系统服务':
				$("#description").attr('placeholder','请描述您所选择的服务请求的具体信息。');
				$('#descriptionAddress').removeClass('ng-hide');
				$('#addressTitle').removeClass('ng-hide');
				break;
			case '应用系统服务':
			case '其他服务':
				$("#description").attr('placeholder','请描述您所选择的服务请求的具体信息以及用户所在办公地点。');
				$('#descriptionAddress').addClass('ng-hide');
				$('#addressTitle').addClass('ng-hide');
				break;
			default:
		}

		return false;
	};

	$scope.eventDispatch = function() {

		if ($scope.formData.category == undefined || $scope.formData.category == '') {
			var alertPopup = $ionicPopup.alert({
				title : '输入错误',
				template : '请选择服务请求类型！'
			});
			return;
		}
		if ($scope.formData.description == undefined || $scope.formData.description == '') {
			var alertPopup = $ionicPopup.alert({
				title : '输入错误',
				template : '请输入信息描述！'
			});
			return;
		}
		if($scope.formData.title=='桌面OA服务'||$scope.formData.title=='会议系统服务') {
			if ($scope.formData.descriptionAddress == undefined || $scope.formData.descriptionAddress == '') {
				var alertPopup = $ionicPopup.alert({
					title: '输入错误',
					template: '请输入地址信息描述！'
				});
				return;
			}
		}
		if($scope.images_url && !$scope.formData.weixinPhotoId) {
			var alertPopup = $ionicPopup.alert({
				title : '暂缓提交',
				template : '照片还未上传完成,请过一会再提交服务请求！'
			});
			return;
		}

		if( $scope.formData.category == 'SERVICEREQ_CATEGORY_50' || $scope.formData.category == 'SERVICEREQ_CATEGORY_40'){
			$scope.formData.descriptionAddress = '';
		}

		var paramdata = {
			title : $scope.formData.title,
			category: $scope.formData.category,
			description : $scope.formData.description,
			files:$scope.fileids
		};
		if ($scope.formData.majorevent == true) {
			paramdata.majorevent = "Y";
		} else {
			paramdata.majorevent = "N";
		}
		var reqdata = {
			'method' : 'ServiceReqDispatch',
			'remark1': $scope.formData.descriptionAddress||'',
			'param' : JSON.stringify(paramdata),
			'weixinPhotoId': $scope.formData.weixinPhotoId, //'1rctdO_G1F97xF9AUx6ZbcksMVkD3EoiGll3tKC22Dao',
			'dataFrom' : 'weixin'
		};

		 //alert(JSON.stringify(paramdata))
		 //return;

		App.ajaxPost(OpenAPI.requrl, $.param(reqdata), function(data){
			
			App.myNotice("新增服务请求成功");
			window.history.back();
		});
	}

  $scope.showActionsheet = function(){
	wx.chooseImage({
	    count: 1, // 默认9
	    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
	    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
	    success: function (res) {
	    	if(res.localIds.length > 0) {
	    		setTimeout(function() {
	  				$('#wexinUploadImg').attr('src', res.localIds[0]);
	  				$('#wexinUploadImgContainer').css('display', 'block');

	  				$scope.images_url = res.localIds[0];

		    		// 上传至微信服务器
		    		wx.uploadImage({
					    localId: res.localIds[0], // 需要上传的图片的本地ID，由chooseImage接口获得
					    isShowProgressTips: 1, // 默认为1，显示进度提示
					    success: function (res1) {
					        $scope.formData.weixinPhotoId = res1.serverId;
					    }
					});
		    	}, 100);
	    	}
	    }
	});
  };

  $scope.delimg = function() {
  	$('#wexinUploadImg').attr('src', '');
	$('#wexinUploadImgContainer').css('display', 'none');

  	$scope.images_url = null;
  	$scope.formData.weixinPhotoId = null;
  }

});

// 服务请求列表
appControllers.controller('FwqqListCtrl', function($scope, $http, $state, $stateParams) {

	var p = {
		//"type" : "ServiceReq",
		"type" : "mobileRequest",
		"dbtype":'0'
	};
	var reqdata = {
		'method' : 'OrderList',
		'param' : JSON.stringify(p),
		'fromType': 'weixin'
	};

	if($stateParams.comment === "true") {
		reqdata.comment = true;
	}

	$scope.scrollItems = [];
	$scope.hasdata = true;

	var cacheusername = Store.loadObject("cacheusername");
	var expiredTime = 48*60*60*1000;
	//var processNames = ['准备服务请求','验证和记录','分派工单','实施交付/投诉处理','用户确认','关闭工单','绩效评分','归档','处理完成'];

	App.ajaxPost(OpenAPI.requrl, $.param(reqdata), function(data){
		for (var i = 0; i < data.object.length; i++) {
			var obj = data.object[i];
			/*if (obj.statu == "0") {
			 obj.statuname = "未签收";
			 } else if (obj.statu == "1") {
			 obj.statuname = "已签收";
			 } else if (obj.statu == "2") {
			 obj.statuname = "已结束";
			 } else {
			 obj.statuname = "---";
			 }*/
			if(obj && obj.endDate && obj.endDate > 0) {
				if(obj.hasOpinion || ((new Date()).getTime()-obj.endDate) > expiredTime) {
					obj.commentTitle = "查看评价";
					obj.commentReadonly = true;
				}else if(obj.starterLoginId == cacheusername) {
					obj.commentTitle = "我要评价";
					obj.commentReadonly = false;
				}
			}

			if(obj && obj.statuname) {
				obj.processName = obj.statuname;
				// var idx = processNames.indexOf(obj.statuname);
				// if(idx < 5 && idx >= 0) {
				// 	obj.processName = '正在处理';
				// }else if(idx >= 5) {
				// 	obj.processName = '处理完成';
				// }else {
				// 	console.log('无法识别的流程节点名称:' + obj.statuname);
				// }
			}

			$scope.scrollItems.push(obj);
		}
		if(data.object.length==0){
			$scope.hasdata = false;
		}
	});

	$scope.detail = function(obj) {

		$state.go('fuwuqingqiudetail', {
			'id' : obj.serialno
		});
	};

	$scope.comment = function(obj) {
		window._pp_commentReadonly = obj.commentReadonly;
		$state.go('add-comment', {
			'id' : obj.serialno
		});
	}
});

// 服务请求详情查询
appControllers.controller('Fwqqdetail', function($scope, $http, $stateParams) {

	App.setScope($scope);
	App.userquery();
	$scope.isRemind = false;

	var p = {
		"serialno" : $stateParams.id
	};

	var reqdata = {
		'method' : 'OrderQuery',
		'param' : JSON.stringify(p)
	};

	App.ajaxPost(OpenAPI.requrl, $.param(reqdata), function(data){

		var obj = data.object;
		var user = Session.loadObject("user");
		obj.typeName=App.getTypeName(obj.category);
		obj.description += !!obj.remark1?"<br/><br/>"+obj.remark1:"";

		$scope.data = obj;
		$scope.data.serialno = $stateParams.id;

		if(user) {
			$scope.userinfo = user;
		}

		if(data.object.image) {
			$('#wexinDownloadImg').attr('src', data.object.image);
			$('#wexinDownloadImgContainer').css('display', 'block');
		}

	});

});

// 催单请求列表
appControllers.controller('remindListCtrl', function($scope, $http, $state) {

	$scope.scrollItems = [];
	$scope.hasdata = true;

	var cacheusername = Store.loadObject("cacheusername");
	var expiredTime = 48*60*60*1000;
	//var processNames = ['准备服务请求','验证和记录','分派工单','实施交付/投诉处理','用户确认','关闭工单','绩效评分','归档','处理完成'];

	App.ajaxPost(OpenAPI.getRemindMeUrl, "", function(data){

		for (var i = 0; i < data.list.length; i++) {
			var obj = data.list[i];
			obj.commentTitle = "催单";
			$scope.scrollItems.push(obj);
		}
		if(data.list.length==0){
			$scope.hasdata = false;
		}
	});

	$scope.detail = function(obj) {
		$state.go('remindDetail', {
			'id' : obj.serialNo,
			'nodeLsh' : obj.nodeLsh,
			'flowLsh' : obj.flowLsh
		});
	};

	//催单
	$scope.remindMe = function(obj) {
		var reqdata = {
			'nodeLsh' : obj.nodeLsh,
			'flowLsh' : obj.flowLsh,
			'serialNo': obj.serialNo
		};
		App.ajaxPost(OpenAPI.setRemindMeUrl, $.param(reqdata), function(data){
			if( data.result ){
				App.myNotice("催单成功");
			}else{
				App.myNotice(data.message);
			}
		});
	}
});

// 催单请求详情查询
appControllers.controller('remindDetailCtrl', function($scope, $http, $stateParams) {

	App.setScope($scope);
	App.userquery();
	$scope.isRemind = true;

	var p = {
		"serialno" : $stateParams.id
	};

	var reqdata = {
		'method' : 'OrderQuery',
		'param' : JSON.stringify(p)
	};

	App.ajaxPost(OpenAPI.requrl, $.param(reqdata), function(data){

		var obj = data.object;
		var user = Session.loadObject("user");
		obj.typeName=App.getTypeName(obj.category);
		obj.description += !!obj.remark1?"<br/><br/>"+obj.remark1:"";

		$scope.data = obj;
		$scope.data.serialno = $stateParams.id;

		if(user) {
			$scope.userinfo = user;
		}

		if(data.object.image) {
			$('#wexinDownloadImg').attr('src', data.object.image);
			$('#wexinDownloadImgContainer').css('display', 'block');
		}

	});

	//催单
	$scope.remindMe = function(obj) {
		var reqdata = {
			'nodeLsh' : $stateParams.nodeLsh,
			'flowLsh' : $stateParams.flowLsh,
			'serialNo': obj.serialno
		};
		App.ajaxPost(OpenAPI.setRemindMeUrl, $.param(reqdata), function(data){
			if( data.result ){
				App.myNotice("催单成功");
			}else{
				App.myNotice(data.message);
			}
		});
	}

});

// 意见反馈列表
appControllers.controller('suggestionListCtrl', function($scope, $http, $state,$timeout,$ionicPopup) {

	$scope.scrollItems = [];
	$scope.hasdata = true;
	$scope.formData={};

	var cacheusername = Store.loadObject("cacheusername");

	App.ajaxPost(OpenAPI.suggestionMyUrl, "", function(data){

		for (var i = 0; i < data.list.length; i++) {
			var obj = data.list[i];
            obj.commentTitle = (obj.status === "未读")?"删除":"";
			//替换代码里面的空格然后解码
            obj.reply = decodeURIComponent(decodeURI(obj.reply.replace(/%2B/g," ")));
			//obj.reply = obj.reply || "暂无回复内容";
            obj.content = decodeURIComponent(decodeURI(obj.content.replace(/%2B/g," ")));
			$scope.scrollItems.push(obj);
		}
		if(data.list.length==0){
			$scope.hasdata = false;
		}
	});

	$scope.delete = function(obj) {
        var confirmPopup = $ionicPopup.confirm({
            title: '提示信息',
            template: '你确定要删除该条记录?'
        });
        confirmPopup.then(function(res) {
            if(res) {
                var reqdata = {
                    'id' : obj.id
                };
                App.ajaxPost(OpenAPI.suggestionDeleteUrl, $.param(reqdata), function(data){
                    if( data.result ){
                        App.myNotice("删除成功");
                        $state.reload();
                    }else{
                        App.myNotice(data.message);
                    }
                });
            }
        });
	};

	//添加意见反馈
	$scope.add = function(obj) {
        var suggestion =$scope.formData.suggestion;
        if (suggestion == undefined || suggestion == '') {
            var alertPopup = $ionicPopup.alert({
                title : '输入错误',
                template : '请输入您的反馈意见！'
            });
            return false;
        }
		var reqdata = {
			'content' : suggestion
		};
		App.ajaxPost(OpenAPI.suggestionSaveUrl, $.param(reqdata), function(data){
			if( data.result ){
				App.myNotice("您的意见已经成功反馈!");
                $timeout(function(){
                    $state.reload();
                },1000);
			}else{
				App.myNotice(data.message);
			}
		});
	}
});


appControllers.controller('LoginFormCtrl', function($rootScope, $scope, $http,
		$location, $ionicPopup, $state) {

	$rootScope.isdisabled=false;

	var paramsComment = {
		method: 'NeedCommentNum',
		param: JSON.stringify({type: 'mobileRequest', dbtype : '0'}),
		fromType: 'weixin',
		comment: 'true'
	}
	var paramsWork = {
		method: 'NeedCommentNum',
		param: JSON.stringify({type: 'mobileRequest', dbtype : '0'}),
		fromType: 'weixin'
	}

	// OpenAPI.requrl = 'http://itscomment.changan.com.cn:9091/mobile/api'
	// OpenAPI.remindSize = 'http://10.64.18.194:8080/itsm17/remind/mySize'

	// 评论数量
	App.ajaxPost(OpenAPI.requrl, $.param(paramsComment), function(data){
		$scope.reqSize = Math.min(data.object, 99)
	});
	// 催单数量
	App.ajaxPost(OpenAPI.remindSize, '', function(data){
		$scope.remindSize = Math.min(data.count, 99)
	});
  // 工单数量
	App.ajaxPost(OpenAPI.requrl, $.param(paramsWork), function(data){
		$scope.workSize = Math.min(data.object, 99)
	});

	$scope.login = function(action) {
		if(G_DEBUGMOUDE){
			// 测试
			// var alertPopup = $ionicPopup.alert({
			// 	title : '测试',
			// 	template : window.location.href
			// });

			 var username = '18696531031';
			 var pwd = '654321';

			 var reqdata = {
			 	'method' : 'login',
			 	'param' : JSON.stringify({username:username, pwd: pwd})
			 };

			 App.ajaxPost(OpenAPI.requrl, $.param(reqdata), function(data){

			 	var usertype = data.object.usertype;
				Session.saveObject("user", data.object);
			 	Session.saveObject("usertype", usertype);

			 	Store.saveObject("cacheusername",username);

			 	$rootScope.usertype = Session.loadObject("usertype");

			 	//alertPopup.then(function(){
			 		if(action == 'service') {
			 			$state.go('fuwuqingqiu-wx');
			 		}else if(action == 'history') {
			 			$state.go('fuwuqingqiulist');
			 		}else if(action == 'comment') {
			 			$state.go('fuwuqingqiulist',{ comment: true });
			 		}else if(action == 'remind') {
						$state.go('remindList');
					}else if(action == 'suggestion') {
						$state.go('suggestionList');
					}
			 	//});
			 });
		}else{
			if(action == 'service') {
				$state.go('fuwuqingqiu-wx');
			}else if(action == 'history') {
				$state.go('fuwuqingqiulist');
			}else if(action == 'comment') {
				$state.go('fuwuqingqiulist',{ comment: true });
			}else if(action == 'remind') {
				$state.go('remindList');
			}else if(action == 'suggestion') {
				$state.go('suggestionList');
			}
		}
	};

	$scope.genValidateCode = function() {
		var seed = new Array('abcdefghijklmnopqrstuvwxyz',
			'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789'); // 创建需要的数据数组
		var idx, i;
		var result = ''; // 返回的结果变量
		for (i = 0; i < 4; i++) // 根据指定的长度
		{
			idx = Math.floor(Math.random() * 3); // 获得随机数据的整数部分-获取一个随机整数
			result += seed[idx].substr(Math.floor(Math.random()
				* (seed[idx].length)), 1);// 根据随机数获取数据中一个值
		}

		$scope.validatecode = result;

		Session.saveObject("validcode", result);

		return result; // 返回随机结果
	};

	$scope.validatecode = $scope.genValidateCode();
});

appControllers.controller('addCommentCtrl', function($scope, $http,$state, $stateParams,$ionicPopup) {
//angular.module('ItsmApp').controller('addCommentCtrl', function($scope, $http,$state, $stateParams) {

	var user = Session.loadObject("user");

	$scope.formData={
		grade: 4,
		serviceGrade: 4,
		isReadonly:  false
	};

	if($stateParams.id) {
		$scope.formData.isReadonly = window._pp_commentReadonly;

		App.ajaxPost(OpenAPI.getCommentUrl + $stateParams.id, {}, function(data){
			$scope.formData.grade = data.data.grade;
			$scope.formData.serviceGrade = data.data.serviceGrade;
			$scope.formData.content = data.data.content;
		}, function(){
		});
	}

	$scope.fixText=function(text,num){
		if ($scope.formData.isReadonly) {
			return
		}
		$('.add-commoent-prize span').removeClass('active');
		$('.add-commoent-prize span').eq(num).addClass('active');
		$scope.formData.content = text;
	}
	
	$scope.fixText1=function(num){
    if ($scope.formData.isReadonly) {
      return
    }
		$('.add-commoent-prize-1 span').removeClass('active');
		$('.add-commoent-prize-1 span').eq(num).addClass('active');
		$scope.formData.serviceGrade = num + 3;
	}
	
	$scope.fixText2=function(num){
    if ($scope.formData.isReadonly) {
      return
    }
		$('.add-commoent-prize-2 span').removeClass('active');
		$('.add-commoent-prize-2 span').eq(num).addClass('active');
		$scope.formData.grade = num + 3;
	}


	$scope.dosubmit=function(){

		if($scope.formData.content==undefined || $scope.formData.content.trim() ==""){
			var alertPopup = $ionicPopup.alert({
				title : '输入错误',
				template : '请输入内容描述'
			});
			return;
		}

		var p = {
			"userid" : user.userid,
			"username" : user.name
		};
		var reqdata = {
			'method' : 'NoteAdd',
			'param' : JSON.stringify(p),
			"content" : $scope.formData.content,
			"workOrderId": $stateParams.id,
			"grade": $scope.formData.grade,
			"serviceGrade": $scope.formData.serviceGrade
		};

		App.ajaxPost(OpenAPI.saveCommentUrl, $.param(reqdata), function(data){
			App.myNotice("提交成功");
			window.history.back();
			//setTimeout(function(){
			//	window.location.href = '../itsm-prize/index.html'
			//},800)
		});
	}
});
